#version 330

uniform mat4x4 u_View;

uniform int u_numLights;
uniform vec3 u_lightColor[8];
uniform vec3 u_lightPosition[8];
uniform float u_cutoffFar[8];
uniform float u_fadeFar[8];

#ifdef TX_COLOR
uniform sampler2D u_Texture;
#endif

in vec3 fs_Normal;
in vec3 fs_Position;

#ifdef TX_COLOR
in vec2 fs_txCoord;
#else
in vec3 fs_Color;
#endif

out vec3 out_Color;

vec3 lightCalc(in vec3 lPos, in vec3 fPos, in vec3 normal, in vec3 color, in float cutoffFar, in float fadeFar) {
	float dist = distance(lPos, fPos);
	float attenuate = 1.0f;
	
	if(dist > cutoffFar)
		attenuate = 0.0f;
	else if(dist > fadeFar)
		attenuate -= (dist - fadeFar)/(cutoffFar - fadeFar);

	return attenuate*color*(max(dot(normalize(lPos - fPos), normal), 0));
}

void main(void)
{
/*
	if(!gl_FrontFacing) {
		discard;
		return;
	}
*/
	float blendWeight = .4f;
	vec3 lightSum = vec3(.0f,.0f,.0f);
	vec3 normal = normalize(fs_Normal);
	
	for(int i = 0; i < u_numLights; ++i)
		lightSum += blendWeight*lightCalc((u_View*vec4(u_lightPosition[i], 1.0f)).xyz, fs_Position, normal, u_lightColor[i], u_cutoffFar[i], u_fadeFar[i]);
	
#ifdef TX_COLOR
	out_Color = (texture(u_Texture, fs_txCoord).rgb * .8f)*lightSum;
#else
	out_Color = (fs_Color*.8f)*lightSum;
#endif
	
    //out_Color = fs_Normal*.5f + .5f;
}